<template>
<div class="RolePermission">
    <el-row>
        <el-col :span="24">
            <el-card>
                <el-form :inline="true" :model="roleForm">
                    <el-form-item label="角色名称">
                        <el-input label-width="250" maxlength="10" show-word-limit clearable v-model="roleForm.roleName" placeholder="请输入"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="search">查询</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="default" @click="reset">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-card>
        </el-col>
    </el-row>

    <el-row>
        <el-col :span="24">
            <el-card shadow="never">
                <!--  @current-change="handleCurrentChange" -->
                <el-table :data="roleList" align="center" border style="width: 100%" highlight-current-row>
                    <el-table-column align="center" prop="roleName" width="150px" label="角色名称"></el-table-column>
                    <el-table-column align="center" prop="roleCode" width="150px" label="角色编号"></el-table-column>
                    <el-table-column align="center" prop="createTime" width="250px" label="创建时间">
                        <template slot-scope="scope">
                            {{ scope.row.createTime | formatDate }}
                        </template>
                    </el-table-column>
                    <el-table-column align="center" prop="createPerson" width="200px" label="创建人"></el-table-column>
                    <el-table-column align="center" width="150px" label="有效">
                        <template slot-scope="scope">
                            <i class="el-icon-check" v-if="scope.row.roleStatus === 1"></i>
                            <i class="el-icon-close" v-else></i>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" prop="remark" label="角色描述"></el-table-column>

                    <el-table-column label="操作" width="200">
                        <template slot="header">
                            <el-button type="primary" size="default" icon="el-icon-plus" @click="addOrEditRole(false)">新建</el-button>
                        </template>
                        <template slot-scope="scope">
                            <el-button v-show="false" type="text" size="small" :disabled="scope.row.roleId==showRoleId" @click="handleCurrentChange(scope.row)">授权</el-button>
                            <el-button type="text" size="small" @click="addOrEditRole(scope.row.roleId)">修改</el-button>
                            <el-button type="text" size="small" @click="deleteHandle(scope.row.roleId)">删除</el-button>
                        </template>
                    </el-table-column>

                </el-table>
            </el-card>
        </el-col>
        <el-col :span="24" v-if="showRouteList" :key="showRoleId">
            <el-card shadow="never">
                <div slot="header" class="clearfix">
                    <span>设置 - <span style="background-color: red;color:#fff;">{{showRoleName}}</span> - 角色路由权限</span>
                </div>
                <el-table :data="routeList" row-key="name" border :tree-props="{children: 'children', hasChildren: 'hasChildren'}" ref="multipleTable" tooltip-effect="dark" @select-all="selectAll" @selection-change="handleSelectionChange" default-expand-all>
                    <el-table-column type="selection" width="45">
                    </el-table-column>
                    <el-table-column prop="meta.title" label="路由名称" sortable width="280">
                    </el-table-column>
                    <!-- <el-table-column prop="name" label="路由键值" sortable width="280">
                    </el-table-column> -->
                    <!-- <el-table-column prop="parent" label="上级" sortable width="280">
                    </el-table-column> -->
                    <el-table-column prop="path" label="路由地址"></el-table-column>
                </el-table>
            </el-card>
        </el-col>
    </el-row>

    <!-- 新增角色弹框 -->
    <el-dialog :title="isAddOrEdit ? '新建角色' : '修改角色'" :visible.sync="isAddRole" width="40%" :destroy-on-close="true">
        <el-form :model="form" ref="form" :rules="rules" label-width="100px" :inline="false" size="normal" @keyup.enter.native="onSubmit()">

            <el-row>
                <el-col :span="24">

                    <el-form-item label="角色编号" prop="roleCode">
                        <el-input v-model="form.roleCode" maxlength="10" show-word-limit placeholder="角色编号"></el-input>
                    </el-form-item>
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="form.roleName" maxlength="10" show-word-limit placeholder="角色名称"></el-input>
                    </el-form-item>

                    <el-form-item label="角色描述" prop="remark">
                        <el-input type="textarea" v-model="form.remark" maxlength="255" show-word-limit placeholder="角色描述"></el-input>
                    </el-form-item>

                </el-col>

                <el-col :span="12">

                    <el-form-item size="mini" label="授权" >
                        <el-tree :data="menuList" :props="menuListTreeProps" node-key="menuId" ref="menuListTree" :default-expand-all="false" show-checkbox>
                        </el-tree>
                        <!-- <el-tree :data="routeList" :props="menuListTreeProps" 
                             node-key="name" ref="menuListTree" :default-expand-all="false" show-checkbox>
                        </el-tree> -->
                    </el-form-item>

                </el-col>
            </el-row>

        </el-form>

        <span slot="footer" class="dialog-footer">
            <el-button @click="exit()">取消</el-button>
            <el-button type="primary" @click="onSubmit('form')">确定</el-button>
        </span>

    </el-dialog>
</div>
</template>

<script>
//

// import AddRoleOREditRole from "./components/AddRoleOREditRole";//增加角色或编辑角色的模态框
import axios from "@/api/request.js";
export default {
    name: "RolePermission",
    components: {
        // AddRoleOREditRole,
    },
    data() {
        return {
            showRoleId: "",
            showRoleName: "",
            showRouteList: false,
            showRouteArray: ['Map', 'TaskPlann', 'TaskPlanningList', 'NamedManagement', 'Rule', 'NotApproved', 'AllData', 'MyData', 'MyTaskList', 'MyTask', 'AuditableData', 'AllStatistics', 'NoLongerAudit', 'DataResource'],
            multipleSelection: [],
            //获取角色列表参数
            roleForm: {
                roleName: "",
                pageNum: 1,
                roleCode: "",
                pageSize: 10,
            },
            menuList: "",
            menuListTreeProps: {
                label: 'name',
                children: 'children'
            },
            // 获取的参数的总数
            total: 0,
            // // 增加角色模态框
            isAddRole: false,
            form: {
                roleCode: "",
                roleName: "",
                remark: "",
                roleStatus: 0,
            },
            // 获取到的角色列表
            roleList: [],
            // 重置分页使用的
            isresetPaging: false,
            // 开启模态框的内容
            openType: 0,
            EditData: {},
            //正则验证
            rules: {
                roleCode: [{
                    required: true,
                    message: "角色编号不能为空",
                    trigger: "blur",
                }, ],
                roleName: [{
                    required: true,
                    message: "角色名称不能为空",
                    trigger: "blur",
                }, ],
            },
            disabled: false,
            isAddOrEdit: true,
            // 临时key, 用于解决tree半选中状态项不能传给后台接口问题.
            tempKey: -666666,
        };
    },
    created() {
        this.getRoleList();
    },
    mounted() {

    },
    computed: {
        routeList() {
            let routeList = this.$router.options.routes[0].children;
            let _this = this;
            let filter = function (arr) {
                return arr.filter((item) => {
                    if (item.children && item.children.length) {
                        item.children = filter(item.children)
                    }
                    item.label = item.meta.title
                    return !item.hidden
                })
            }
            let f = filter(routeList);
            return f
        },
    },
    methods: {
        selectAll(rows) {
            this.$nextTick(function () {
                rows.forEach((item) => {
                    if (item.children && item.children.length) {
                        this.selectAll(item.children)
                    }
                    if (this.showRouteArray.join(',').indexOf(item.name) != -1) {
                        this.$refs.multipleTable.toggleRowSelection(item);
                    }
                })
            })
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
            console.log(this.multipleSelection);
            this.multipleSelection.forEach((item)=>{
                this.showRouteArray.push(item.name)
            })
            console.log([...new Set(this.showRouteArray)]);
        },
        handleCurrentChange(row) {
            if(row.roleId == this.showRoleId){
                this.showRouteList = false
            }
            this.showRoleId = row.roleId
            this.showRoleName = row.roleName
            this.showRouteList = true
            this.selectAll(this.routeList)
        },
        exit() {
            this.form = {
                roleCode: "",
                roleName: "",
                remark: "",
                roleStatus: 0,
            };
            this.isAddRole = false;
        },
        treeDataTranslate(data, id = 'id', pid = 'parentId') {
            var res = []
            var temp = {}
            for (var i = 0; i < data.length; i++) {
                temp[data[i][id]] = data[i]
            }
            for (var k = 0; k < data.length; k++) {
                if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
                    if (!temp[data[k][pid]]['children']) {
                        temp[data[k][pid]]['children'] = []
                    }
                    if (!temp[data[k][pid]]['_level']) {
                        temp[data[k][pid]]['_level'] = 1
                    }
                    data[k]['_level'] = temp[data[k][pid]]._level + 1
                    temp[data[k][pid]]['children'].push(data[k])
                } else {
                    res.push(data[k])
                }
            }
            return res
        },
        addOrEditRole(id) {
            this.form.id = id
            if (id) {
                this.isAddOrEdit = false;
            } else {
                this.isAddOrEdit = true
            }
            this.$fishing.createRolePermissionTree().then((res) => {
                this.disabled = false;
                this.isAddRole = true;
                this.menuList = this.treeDataTranslate(res.data, 'menuId')

                this.$nextTick(() => {
                    this.$refs['form'].resetFields()
                    this.$refs.menuListTree.setCheckedKeys([])
                })

                if (this.form.id) {
                    this.$fishing.getRoleDetailInfo(this.form).then((res) => {
                        console.log(res)
                        this.form.roleName = res.data.roleName;
                        this.form.remark = res.data.remark;
                        this.form.roleStatus = res.data.roleStatus;
                        this.form.roleCode = res.data.roleCode;
                        if (res.data.menuIdList != null) {
                            var idx = res.data.menuIdList.indexOf(this.tempKey)
                            if (idx !== -1) {
                                res.data.menuIdList.splice(idx, res.data.menuIdList.length - idx);
                            }
                            this.$refs.menuListTree.setCheckedKeys(res.data.menuIdList)
                        }
                    });
                }
            });

        },
        // 查询方法
        search() {
            this.getRoleList(this.roleForm);
        },
        // 重置方法
        reset() {
            this.roleForm = {
                roleName: "",
                pageNum: 1,
                pageSize: 10,
            };
            this.isresetPaging = true;
            this.getRoleList();
        },
        // 获取角色列表
        getRoleList(roleForm) {
            this.$common.RolePermission(roleForm).then((res) => {
                this.roleList = res.data.list;
                // res.data.list.forEach((item) => {
                //     this.roleList.push(item)
                // })
            });
        },

        deleteHandle(id) {
            this.$confirm('警告警告！此操作将永久删除该角色，可能影响对应帐户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {

                axios.post(
                    `rbac/sys/role/delete`, {
                        params: {
                            "roleIds": id
                        }
                    }).then((res) => {
                    if (res && res.errorCode == "00000") {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.getRoleList();
                    }
                });

            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });

        },
        // 关闭模态框
        changeIsAddRole(bool) {
            this.isAddRole = bool;
        },

        onSubmit(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.form.menuIdList = [].concat(this.$refs.menuListTree.getCheckedKeys(), [this.tempKey], this.$refs.menuListTree.getHalfCheckedKeys())
                    this.$fishing.createRole(this.form).then((res) => {
                        if (res && res.errorCode == "00000") {
                            this.$message({
                                message: '操作成功',
                                type: 'success',
                                duration: 1500,
                                onClose: () => {
                                    this.changeIsAddRole(false);
                                    this.getRoleList();
                                    this.form = {
                                        roleCode: "",
                                        roleName: "",
                                        remark: "",
                                        roleStatus: 0,
                                    }
                                }
                            })
                        } else {
                            this.$message.error(res.errorMsg)
                        }

                    })
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
    },
};
</script>

<style lang="scss">
.RolePermission {
    width: 98%;
    margin: 0 0.5%;
    background: white;
    height: 100%;
    padding: 10px;

    .operation {
        padding: 20px 0;
    }
}
</style>
